<?php
namespace app\api\controller;
use app\common\library\Sms as Smslib;
use think\facade\Db;
use app\common\controller\Api;

/**
 * @author swq
 * @date 2020-10-14
 * 登录接口
*/

class Login extends Api
{
	protected $noNeedLogin = ['send', 'login', 'decryptInfo'];
    // protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 发送验证码
     *
     * @param string $mobile 手机号
     * @param string $event  事件名称
     */
    public function send()
    {
        $mobile = $this->request->param('mobile');

        if(! $mobile){
            $this->error(__('手机号不能为空！'));
        }
        $last = Smslib::get($mobile);
        if ($last && $_SERVER['REQUEST_TIME'] - $last['createtime'] < 60) {
            $this->error(__('发送频繁，请稍后重试'));
        }
        $ret = Smslib::send($mobile, null, 1, 'login');
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败，请稍后重试'));
        }
    }

    /**
     * 会员登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function login()
    {
        $mobile = $this->request->param('mobile');
        $captcha = $this->request->param('captcha');
        if (! $mobile || ! $captcha) {
            $this->error(__('参数错误'));
        }

        if (! Smslib::check($mobile, $captcha, 'login')) {
            $this->error(__('验证码错误'));
        }
        $user = \app\common\model\User::where('mobile',$mobile)->find();
        if ($user) {
            if ($user->status != '1') {
                $this->error(__('账号已被禁用'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile);
        }
        if ($ret) {
//            Smslib::flush($mobile);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('登陆成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /********************************************天翼选单点登录start*******************************************************/

    /**
     * 参数加密
    */
    public function encryptionInfo()
    {
        $mobile = $this->request->post('mobile');

        if (!$mobile) $this->error('手机号不能为空！');

        $mobile = $this->passport_encrypt($mobile, 'HB13000002');

        $data = [
            'ticket' => $mobile,
            'channel' => 'HB13000002',
        ];

        $this->success('获取成功！', $data);
    }   

    /**
     * 参数 解密
    */
    public function decryptInfo()
    {
        $post = $this->request->post(); 
        if (!$post['ticket'])  return json(['rspCode' => 400, 'rspDesc' => 'ticket不能为空！']);

        $time = strtotime(substr($post['requestNo'], 0, 14)) + 1200;
        
        if ($time < time()) return json(['rspCode' => 400, 'ticket' => 'ticket已过期！']);

        if ($post['channel'] != 'HB13000002') return json(['rspCode' => 400, 'channel' => 'channel错误！']);

        $mobile = $this->passport_decrypt($post['ticket'], 'HB13000002');
        
        return json(['rspCode' => "0000", 'rspDesc' => '成功', 'rspJsonStr' => ['productNo' => $mobile]]);
    }

    /**
     * 参数加密
     * @param txt 数据 string
     * @param key 秘钥串 string
    */
    public function passport_encrypt($txt, $key = 'HB13000002')  
    {  
        srand((double)microtime() * 1000000);  
        $encrypt_key = md5(rand(0, 32000));  
        $ctr = 0;  
        $tmp = '';  
        for($i = 0;$i < strlen($txt); $i++) {  
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;  
            $tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);  
        }  
        return urlencode(base64_encode($this->passport_key($tmp, $key)));  
    }  
    
    /**
     * 参数解密
     * @param txt 加密数据 string
     * @param key 秘钥串 string
    */
    public function passport_decrypt($txt, $key = 'HB13000002') 
    {  
        $txt = $this->passport_key(base64_decode(urldecode($txt)), $key);  
        $tmp = '';  
        for($i = 0;$i < strlen($txt); $i++) {  
            $md5 = $txt[$i];  
            $tmp .= $txt[++$i] ^ $md5;  
        }  
        return $tmp;  
    }  
     
    public function passport_key($txt, $encrypt_key) 
    {  
        $encrypt_key = md5($encrypt_key);  
        $ctr = 0;  
        $tmp = '';  
        for($i = 0; $i < strlen($txt); $i++) {  
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;  
            $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];  
        }  
        return $tmp;  
    }
}
